/**
 * 
 *
 * @author fan.ch
 * @date 2017-07-01
 * @copyright jianjia.com
 *
 */
'use strict';
var express = require('express');
var router = express.Router();
var request = require('request');
var mongoose = require('mongoose');
var url = require("url");
var path = require('path');
var db = require(path.join(__dirname, "../../tools/basicServer.js"));
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var util = require('util');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: false
}));
/*
 * req：type  1、logo 2、上传轮播图
 * res:result: 1,data: url								
 * 
 * */
router.all('/logoUrl', function(req, res, next) {
	function promisifyAsyncFunc() { //调用公共函数db.uploadPic获取参数
		return new Promise((resolve, reject) => {
			db.uploadPic(req, res, function(url, type, loginName, filePath) {
				resolve({
					"url": url,
					"type": type,
					"loginName": loginName,
					"filePath": filePath
				})
			})
		})
	}

	function promisifyAsyncFunc2(passParam) { //调用公共函数db.uploadPic获取参数
		return new Promise((resolve, reject) => {
			db.findOne("log", {
				'name': passParam.loginName
			}, function(docs) {
				resolve({
					"url": passParam.url,
					"type": passParam.type,
					"loginName": passParam.loginName,
					"companyName": docs.companyName,
					"filePath": passParam.filePath
				})
			})
		})
	}

	function promisifyAsyncFunc3(passParam) { //通过查询此公司是否有logo图片，有则更新数据库，没有则插入到数据库
		return new Promise((resolve, reject) => {
			//保存地址到服务器,有则修改，无则添加
			db.findOne("picture", {
				'name': passParam.loginName
			}, function(docs) {
				var updateOrInsertParam = {};
				updateOrInsertParam["name"] = passParam.loginName;
				updateOrInsertParam["companyName"] = passParam.companyName;
				//				updateOrInsertParam["filePath"] = passParam.filePath;
				updateOrInsertParam["logoUrl"] = docs && docs.logoUrl || {};
				updateOrInsertParam["broadcast"] = docs && docs.broadcast || [];
				
				if(passParam.type == 1) {
					updateOrInsertParam.logoUrl = {
						"url": passParam.url,
						"filePath": passParam.filePath
					}
				}
				if(passParam.type == 2) {
					if(docs && !docs.broadcast) { //上传的图片是轮播图
						updateOrInsertParam.broadcast = [];
					}
					updateOrInsertParam.broadcast.push({
						"url": passParam.url,
						"filePath": passParam.filePath
					});
				}
				if(docs && docs.companyName) {
					db.updateOne("picture", {
						"companyName": updateOrInsertParam.companyName
					}, updateOrInsertParam, function(result) {
						if(result) {
							res.send({
								result: 1,
								data: updateOrInsertParam
							})
						}
					})
				} else {
					db.insertOne("picture", updateOrInsertParam, function(result) {
						if(result) {
							res.send({
								result: 1,
								data: updateOrInsertParam
							})
						}
					})
				}
			})

		})
	}
	promisifyAsyncFunc(req).then(promisifyAsyncFunc2).then(promisifyAsyncFunc3)
})
/*
 * @date 2017-07-25
 * @copyright jianjia.com
 * req:name(登录名)
 * res:url (logo的地址)
 * param.type{
 * 		1 logo图片
 * }
 * */
router.all('/getPicByType', function(req, res, next) {
	var param = req.body;
	db.findOne("picture", {
		"name": param.name
	}, function(docs) {
		if(docs) {
			res.send({
				result: 1,
				url: docs
			})

		} else {
			res.send({
				result: -1,
				url: ""
			})
		}
	})
})
/*
 * @date 2017-07-25
 * @copyright jianjia.com
 * req:name(登录名)
 * res:url (logo的地址)
 * param.type{
 * 		1 logo图片
 * }
 * */
router.all('/deletePicByType', function(req, res, next) {
	function searchPromise(req) {
		var newArr = req.body.broadcastUrl; //被删除的url数组
		return new Promise((resolve, reject) => {
			var param = req.body;
			db.findOne("picture", {
				"name": param.name
			}, function(docs) {
				var param = docs.broadcast;

				if(req.body.type == 2) {
					var result = param.filter((item, index, arr) => {
						return item.url != newArr.url
					})
					var obj = {
						"req": req,
						"type": req.body.type,
						"broadcast": result,
						"name": req.body.name,
						"deleteUrl": newArr.filePath
					}
				} else if(req.body.type == 1) {
					var obj = {
						"req": req,
						"type": req.body.type,
						"name": req.body.name
					}
				}

				resolve(obj)
			})
		})
	}

	function deletepromisify1(result) { //删除照片时，先修改数据库的内容
		return new Promise((resolve, reject) => {
			if(result.type == 1) { //删除的是logo
				var temParam = {
					"logoUrl": {}
				}
			} else if(result.type == 2) {
				var temParam = {
					"broadcast": result.broadcast
				}
			}
			var operate = {
				$set: temParam
			}
			db.updateOne("picture", {
				"name": result.name
			}, operate, function(results) {
				if(result.type == 2) { //只有当类型等于2的时候才需要删除，
					resolve(result.deleteUrl)
				} else {
					if(results) {
						res.send({
							result: 1,
						})
					}
				}
			})
		})
	}

	function deletepromisify2(param) { //删除数据库中的地址
		return new Promise((resolve, reject) => {
			console.log("1231333")
			console.log(param)
			fs.unlink(param, function(err, success) {
				if(success) {
					res.send({
						result: 1,
					})
				}
			})
		})
	}
	searchPromise(req).then(deletepromisify1).then(deletepromisify2)
})

function encodeSearchKey(key) {
	const encodeArr = [{
		code: '%',
		encode: '%25'
	}, {
		code: '?',
		encode: '%3F'
	}, {
		code: '#',
		encode: '%23'
	}, {
		code: '&',
		encode: '%26'
	}, {
		code: '=',
		encode: '%3D'
	}];
	return key.replace(/[%?#&=]/g, ($, index, str) => {
		for(const k of encodeArr) {
			if(k.code === $) {
				return k.encode;
			}
		}
	});
}
module.exports = router;